package com.mylib.widget;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.core.content.ContextCompat;

import com.mylib.libcore.R;
import com.mylib.libcore.utils.AppUtil;
import com.mylib.libcore.utils.UIUtils;
import com.tencent.smtt.export.external.interfaces.GeolocationPermissionsCallback;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;


/**
 * @author Administrator
 * @date 2019/12/17-11:43
 * @description 上方带有加载进度条的webview，使用腾讯X5内核
 **/
public class ProgressWebView extends WebView implements DownloadListener {

    private int screenWidth;
    private View progressView;
    private OnWebViewListener onWebViewListener;
    private boolean isShowProgressView = true;

    private Context context;

    public ProgressWebView(Context context) {
        this(context, null);
        this.context = context;

    }

    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);

        screenWidth = AppUtil.getDisplayMetrics(getContext()).widthPixels;

        progressView = new View(context);
        progressView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
        addView(progressView);

        ViewGroup.LayoutParams params = progressView.getLayoutParams();
        params.height = 0;
        progressView.setLayoutParams(params);

        initWebSetting();

        this.setDownloadListener(this);
        super.setWebViewClient(new CWebViewClient());
        super.setWebChromeClient(new CWebChromeClient());
    }


    /**
     * 初始化webview相关的设置
     */
    private void initWebSetting() {
        this.setScrollBarSize(0);
        this.getSettings().setBlockNetworkImage(false);
        this.getSettings().setPluginsEnabled(true);
        this.getSettings().setPluginState(WebSettings.PluginState.ON);
        this.getSettings().setSaveFormData(true);
        this.getSettings().setSavePassword(true);
        this.getSettings().setAllowFileAccess(true);
        this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        this.getSettings().setSupportMultipleWindows(false);
        this.getSettings().setJavaScriptEnabled(true);
        this.getSettings().setGeolocationEnabled(true);
        this.getSettings().setDefaultTextEncodingName("utf-8");
        String userAgent = this.getSettings().getUserAgentString()+"android-webview";
        this.getSettings().setUserAgentString(userAgent);



        this.getSettings().setDatabaseEnabled(true);
        //设置定位的数据库路径
        String dir = getContext().getDir("database", Context.MODE_PRIVATE).getPath();
        this.getSettings().setGeolocationDatabasePath(dir);
        //取得缓存路径
        String path = getContext().getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        //设置路径
        this.getSettings().setDatabasePath(path);
        // 开启 DOM storage 功能
        this.getSettings().setDomStorageEnabled(true);
        //设置存储模式
        this.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        this.getSettings().setAppCacheEnabled(true);
        String cachePath = getContext().getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        this.getSettings().setAppCachePath(cachePath);
        // this.getSettings().setAppCacheMaxSize(1024 * 1024 * 10);//设置缓冲大小为10M
        this.getSettings().setAppCacheMaxSize(Long.MIN_VALUE);//设置缓冲大小修改2019-12-17
        // 设置可以支持缩放
        this.getSettings().setSupportZoom(false);
        // 设置出现缩放工具
        this.getSettings().setBuiltInZoomControls(true);
        this.getSettings().setDisplayZoomControls(false);
        //扩大比例的缩放
        this.getSettings().setUseWideViewPort(true);
        //自适应屏幕
        this.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        this.getSettings().setLoadWithOverviewMode(true);
        //设置优先渲染
        this.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);

    }

    @Override
    public void loadUrl(String url) {
        super.loadUrl(url);
    }



    /**
     * 文件下载回调方法
     */
    @Override
    public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse(url));
        getContext().startActivity(intent);
    }

    /**
     * 自定义ChromeClient类，处理加载进度条、文件选择、标题等内容
     */
    public class CWebChromeClient extends WebChromeClient {


        @SuppressLint("CheckResult")
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress > 90) {
                String title = ProgressWebView.this.getTitle();
                if (onWebViewListener != null) {
                    onWebViewListener.onTitleChanged(title);
                }
            }

            Observable.just(newProgress)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Integer>() {
                        @Override
                        public void accept(Integer i) {
                            double proWidth = screenWidth * i / 100.00;
                            ViewGroup.LayoutParams params = progressView.getLayoutParams();
                            params.width = (int) proWidth;
                            progressView.setLayoutParams(params);
                            if (i == 100) {
                                progressView.setVisibility(View.GONE);
                            } else if (isShowProgressView) {
                                progressView.setVisibility(View.VISIBLE);
                            }
                        }
                    });

            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (onWebViewListener != null) {
                onWebViewListener.onTitleChanged(title);
            }
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String s, GeolocationPermissionsCallback geolocationPermissionsCallback) {
            geolocationPermissionsCallback.invoke(s, true, true);
            super.onGeolocationPermissionsShowPrompt(s, geolocationPermissionsCallback);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
            if (onWebViewListener != null) {
                onWebViewListener.onFileChooser(valueCallback, fileChooserParams);
                return true;
            }
            return super.onShowFileChooser(webView, valueCallback, fileChooserParams);
        }
    }


    public class CWebViewClient extends WebViewClient {


        @Override
        public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
            Log.d("webResourceRequest1",webResourceRequest.getUrl()+"");//buy_step1_new.html//met=getUserConfigAddress"
            return super.shouldInterceptRequest(webView, webResourceRequest);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest, Bundle bundle) {
            Log.d("webResourceRequest2",webResourceRequest.getUrl()+"");
            return super.shouldInterceptRequest(webView, webResourceRequest, bundle);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            System.out.println("拦截url>>>"+url);
            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
//            float   contentHeight = dataBinding.progressWebView.getContentHeight() *  dataBinding.progressWebView.getScale() ;
//            int mWebViewTotalHeight =(int) (contentHeight- dataBinding.progressWebView.getHeight());
//            Log.d("appweb=上下可滚动的范围=",mWebViewTotalHeight+"");
//            Log.d("appweb=获取html高度=",dataBinding.progressWebView.getContentHeight()+"");
//            Log.d("appweb=手机上网页缩放比例=",dataBinding.progressWebView.getScale()+"");
//            Log.d("appweb=WebView控件的高度=",dataBinding.progressWebView.getHeight()+"");
//            Log.d("appweb=WebView控件的高度=",dataBinding.progressWebView.getHeight()+"");
//            Log.d("appweb=ww=",dataBinding.progressWebView.getHeight()+"");
//            Log.d("appweb=w=",dataBinding.progressWebView.getHeight()+"");
//            LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) webView.getLayoutParams();
//            linearParams.height = dataBinding.progressWebView.getHeight()+Math.abs(mWebViewTotalHeight);
//            webView.setLayoutParams(linearParams);
            super.onPageFinished(view, url);

        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler handler, SslError sslError) {
            // 接受所有网站的证书，忽略SSL错误，执行访问网页--google ssl 错误
            handler.proceed();
//            sslErrorHandler.cancel(); // Android默认的处理方式-不接受
//            handler.proceed();// 接受所有网站的证书
            super.onReceivedSslError(webView, handler, sslError);
        }
    }



    public void setOnWebViewListener(OnWebViewListener onWebViewListener) {
        this.onWebViewListener = onWebViewListener;
    }

    public interface OnWebViewListener {
        void onTitleChanged(String title);
        void onFileChooser(ValueCallback<Uri[]> valueCallback, WebChromeClient.FileChooserParams fileChooserParams);
        void interceptUrl(String url);//拦截url
    }






}